import Vue from 'vue'
import VueRouter from 'vue-router'
import { Toast } from 'vant'
import store from '@/store'
const login = () => import('@/views/login')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const mine = () => import('@/views/mine')
const video = () => import('@/views/video')

const UserEdit = () => import('@/views/mine/UserEdit')

const article = () => import('@/views/article')
const search = () => import('@/views/search')
const SearchResult = () => import('@/views/search/SearchResult')
const mychat = () => import('@/views/mine/MyChat')
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/layout/home' },
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/mine/edit',
    component: UserEdit
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [{
      name: 'home',
      path: 'home',
      component: home,
      meta: {
        needkeep: true
      }
    }, {
      name: 'ask',
      path: 'ask',
      component: ask
    }, {
      name: 'mine',
      path: 'mine',
      component: mine,
      meta: {
        needLogin: true
      }
    }, {
      name: 'video',
      path: 'video',
      component: video
    }
    ]
  }, {
    name: 'article',
    path: '/article/:id',
    component: article
  }, {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'SearchResult',
    path: '/search/searchresult',
    component: SearchResult
  }, {
    name: 'mychat',
    path: '/mychat',
    component: mychat
  }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  console.log(to, from)
  if (to.meta.needLogin) {
    if (store.state.user.tokenObj.token) {
      next()
    } else {
      Toast('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else { next() }
})
export default router
